<template>
  <div class="dynamic-list">
    <div
      class="dynamic-card"
      v-for="item in dynamics"
      :key="item.dynamicId"
      @click="() => !inPreviewMode && goDetail(item.dynamicId)"
    >
      <div class="more-menu-wrapper" @click.stop>
        <el-dropdown
          trigger="click"
          @command="(command) => handleMenuCommand(command, item)"
        >
          <span class="more-btn">···</span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="report">举报</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 用户信息：点击头像/用户名不跳转 -->
      <div class="user-info" @click.stop="goUserProfile(item.authorId)">
        <img class="avatar" :src="item.avatar" alt="头像" />
        <span class="username">{{ item.username }}</span>
      </div>

      <!-- 标题 & 内容：点击跳转（不加 .stop） -->
      <div class="dynamic-header">
        <h3 class="title">{{ item.dynamicTitle }}</h3>
      </div>
      <div class="content">{{ item.dynamicContent }}</div>

      <!-- 图片区域：点击图片只放大，不跳转 -->
      <div class="image-grid" v-if="item.imagesUrl?.length" @click.stop>
        <div
          class="image-wrapper"
          v-for="(img, index) in item.imagesUrl.slice(0, 3)"
          :key="index"
          @click.stop="previewImage(index, item.imagesUrl)"
        >
          <img :src="img" class="dynamic-image" />

          <!-- 第3张图右上角提示总数 -->
          <div
            v-if="index === 2 && item.imagesUrl.length > 3"
            class="image-count"
            @click.stop="goDetail(item.dynamicId)"
          >
            共 {{ item.imagesUrl.length }} 张
          </div>
        </div>
      </div>

      <el-image-viewer
        v-if="showViewer"
        :url-list="imageList"
        :initial-index="startIndex"
        @close="closePreview"
      />

      <!-- 话题和点赞评论：话题不可跳转，其他区域可跳 -->
      <div class="footer-bar">
        <div class="topics" @click.stop>
          <span
            class="topic"
            v-for="topic in item.topics"
            @click="goTopic(topic.topicId)"
            :key="topic.topicId"
          >
            #{{ topic.topicName }}
          </span>
        </div>
        <div class="stats">
          <span class="stat">💬 {{ item.commentCount }}</span>
          <span class="stat">👍 {{ item.likeCount }}</span>
        </div>
      </div>
    </div>
  </div>
  <!-- 加载更多按钮 -->
  <div class="load-more-wrapper">
    <div v-if="hasMore" class="load-more" @click="loadMore">
      <span class="load-text" :class="{ loading }">
        {{ loading ? '加载中...' : '点击加载更多' }}
      </span>
    </div>
    <div v-else class="no-more">
      <span>没有更多内容了</span>
    </div>
  </div>
  <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllDynamic } from '@/apis/dynamic'
import { useRouter } from 'vue-router'
import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget as reportApi } from '@/apis/report'

const router = useRouter()
const dynamics = ref([])

const showViewer = ref(false)
const imageList = ref([])
const startIndex = ref(0)
const inPreviewMode = ref(false) // ✅ 控制跳转

// const fetchDynamics = async () => {
//   try {
//     const res = await getAllDynamic()
//     if (res.code === '200') {
//       dynamics.value = res.data
//     } else {
//       ElMessage.error(res.message || '获取动态失败')
//     }
//   } catch {
//     ElMessage.error('网络异常，请稍后重试')
//   }
// }

const previewImage = (index, images) => {
  imageList.value = images
  startIndex.value = index
  showViewer.value = true
  inPreviewMode.value = true
}

const closePreview = () => {
  showViewer.value = false
  // 加一个延迟再关闭 preview 模式，避免点击残留触发跳转
  setTimeout(() => {
    inPreviewMode.value = false
  }, 100)
}

const goDetail = (id) => {
  router.push(`/home/dynamic/${id}`)
}

const goUserProfile = (userId) => {
  router.push(`/home/user/${userId}`)
}

const goTopic = (topicId) => {
  router.push(`/home/topic/${topicId}`)
}
// onMounted(fetchDynamics)

//举报相关
const showMenuId = ref(null) // 当前显示菜单的动态ID
const showReportDialog = ref(false)
const reportTarget = ref(null) // 当前举报对象

const handleMenuCommand = (command, item) => {
  if (command === 'report') {
    reportTarget.value = {
      targetId: item.dynamicId,
      targetType: 1,
    }
    showReportDialog.value = true
  }
}

const handleReportSubmit = async (payload) => {
  const finalData = {
    ...payload,
    ...reportTarget.value,
  }

  try {
    const res = await reportApi(finalData)
    if (res.code === '200') {
      ElMessage.success('举报提交成功，平台将尽快处理')
      showReportDialog.value = false
    } else {
      ElMessage.warning(res.message || '举报失败')
    }
  } catch (error) {
    console.error('举报提交出错：', error)
    ElMessage.error('举报失败，请稍后再试')
  }
}

// 分页状态
const page = ref(1)
const size = ref(3)
const hasMore = ref(true)

// 加载数据
const loadDynamics = async () => {
  try {
    const res = await getAllDynamic({
      pageNum: page.value,
      pageSize: size.value,
    })
    if (res.data?.length > 0) {
      // 合并新旧数据（增量加载）
      dynamics.value = [...dynamics.value, ...res.data]
      // 判断是否有更多数据
      hasMore.value = res.data.length === size.value
    } else {
      hasMore.value = false
    }
  } catch (err) {
    ElMessage.error('加载失败：' + err.message)
  }
}

// 初始加载
onMounted(loadDynamics)
const loading = ref(false)

const loadMore = async () => {
  if (!hasMore.value || loading.value) return
  try {
    loading.value = true
    page.value++
    await loadDynamics()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dynamic-list {
  max-height: 100vh; /* 视口高度的70% */
  overflow-y: auto; /* 垂直滚动 */
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-right: 8px; /* 防止滚动条覆盖内容 */

  /* 可选：自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f5f5f5;
}
.dynamic-card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  cursor: pointer;
}
.dynamic-card:hover {
  background: #f8f9fa;
}
.dynamic-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  cursor: zoom-in; /* 鼠标变放大镜 */
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}
.username {
  font-weight: bold;
  font-size: 14px;
}

.dynamic-header {
  margin-bottom: 6px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.content {
  margin-bottom: 10px;
  color: #333;
}

.image-grid {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 8px;
}
.image-wrapper {
  position: relative;
}
.dynamic-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}

/* 第3张图右上角的总数提示 */
.image-count {
  position: absolute;
  top: 6px;
  right: 6px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 8px;
  pointer-events: auto;
  cursor: pointer;
}

.footer-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  font-size: 13px;
  color: #777;
}
.topics {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.topic {
  background-color: #e6f0ff;
  color: #007bff;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 13px;
}
.stats {
  display: flex;
  gap: 16px;
}
.stat {
  display: flex;
  align-items: center;
  gap: 4px;
}

.more-menu-wrapper {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
}
.more-btn {
  cursor: pointer;
  font-size: 20px;
  color: #999;
  user-select: none;
}
.dynamic-card {
  position: relative; /* 用于定位右上角按钮 */
}
.load-more-wrapper {
  margin: 20px 0;
  text-align: center;
}

/* 统一加载/提示区域样式 */
.load-more,
.no-more {
  display: inline-block;
  padding: 12px 24px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

/* 加载更多具体样式 */
.load-more {
  background-color: #f5f5f5;
  color: #666;
}

/* 没有更多提示样式 */
.no-more {
  background-color: transparent;
  color: #999;
  cursor: default;
  padding: 12px 0; /* 减少左右padding */
}
</style>
